<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>订单管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
</head>

<body>
    <div class="layuimini-container">
        <div class="layuimini-main">
            <!-- 搜索条件 -->
            <fieldset class="table-search-fieldset">
                <legend>搜索信息</legend>
                <div style="margin: 10px 10px 10px 10px">
                    <form class="layui-form layui-form-pane" action="">
                        <div class="layui-form-item">
                            <div class="layui-inline">
                                <label class="layui-form-label">系统</label>
                                <div class="layui-input-inline">
                                    <select name="system" lay-search>
                                        <option value="">请选择系统</option>
                                        <option value="安卓">安卓</option>
                                        <option value="ios">ios</option>
                                    </select>
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label">状态</label>
                                <div class="layui-input-inline">
                                    <select name="status" lay-search>
                                        <option value="">请选择状态</option>
                                        <option value="待扫码">待扫码</option>
                                        <option value="进行中">进行中</option>
                                        <option value="已完成">已完成</option>
                                        <option value="登陆失效">登陆失效</option>
                                        <option value="已取消">已取消</option>
                                        <option value="安全验证">安全验证</option>
                                        <option value="待处理">待处理</option>
                                        <option value="已上限">已上限</option>
                                        <option value="即将下线">即将下线</option>
                                    </select>
                                </div>
                            </div>
                            <div class="layui-inline">
                                <label class="layui-form-label">创建时间</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="startDate" id="startDate" placeholder="开始日期" autocomplete="off" class="layui-input">
                                </div>
                                <div class="layui-form-mid">-</div>
                                <div class="layui-input-inline">
                                    <input type="text" name="endDate" id="endDate" placeholder="结束日期" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-inline">
                                <button type="submit" class="layui-btn layui-btn-primary" lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                            </div>
                        </div>
                    </form>
                </div>
            </fieldset>

            <script type="text/html" id="toolbarDemo">
                <div class="layui-btn-container">
                    <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="addOrder"> 新增订单 </button>
                    <button class="layui-btn layui-btn-warm layui-btn-sm" lay-event="exportData"> 导出数据 </button>
                </div>
            </script>

            <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

            <script type="text/html" id="currentTableBar">
                <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="remark">备注</a>
                {{# if(d.status !== '已完成' && d.status !== '已取消') { }}
                <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="cancel">取消</a>
                {{# } }}
                {{# if(d.status === '登陆失效' || d.status === '安全验证' || d.status === '进行中' || d.status === '待处理') { }}
                <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="rescan">重扫</a>
                {{# } }}
            </script>

            <script type="text/html" id="statusTpl">
                {{# if(d.status === '待扫码') { }}
                <span class="layui-badge layui-bg-gray">待扫码</span>
                {{# } else if(d.status === '进行中') { }}
                <span class="layui-badge layui-bg-blue">进行中</span>
                {{# } else if(d.status === '已完成') { }}
                <span class="layui-badge layui-bg-green">已完成</span>
                {{# } else if(d.status === '已取消') { }}
                <span class="layui-badge layui-bg-red">已取消</span>
                {{# } else if(d.status === '登陆失效') { }}
                <span class="layui-badge layui-bg-orange">登陆失效</span>
                {{# } else if(d.status === '安全验证') { }}
                <span class="layui-badge layui-bg-cyan">安全验证</span>
                {{# } else if(d.status === '待处理') { }}
                <span class="layui-badge layui-bg-blue">待处理</span>
                {{# } else if(d.status === '即将下线') { }}
                <span class="layui-badge layui-bg-red">即将下线</span>
                {{# } else if(d.status === '已上限') { }}
                <span class="layui-badge layui-bg-red">已上限</span>
                {{# } }}
            </script>

        </div>
    </div>
    <script src="/lib/layui/layui.js" charset="utf-8"></script>
    <script src="/lib/axios/axios.js" charset="utf-8"></script>
    <script src="/lib/dayjs.js" charset="utf-8"></script>
    <script>
        layui.use(['form', 'table', 'laydate'], function () {
            var $ = layui.jquery,
                form = layui.form,
                table = layui.table,
                laydate = layui.laydate;

            // 日期选择器
            laydate.render({
                elem: '#startDate'
            });
            laydate.render({
                elem: '#endDate'
            });

            let tableIns = table.render({
                elem: '#currentTableId',
                url: '/order/list',
                toolbar: '#toolbarDemo',
                cols: [[
                    { type: "checkbox", width: 50 },
                    { type: "numbers", width: 60, title: '序号' },
                    { field: '_id', width: 80, title: 'ID', sort: true, hide: true },
                    { field: 'orderNumber', width: 180, title: '订单编号', sort: true, templet: function(d) {
                        return '<a href="/order-detail/' + d.orderNumber + '" target="_blank" style="color: #1E9FFF; text-decoration: underline; cursor: pointer;">' + d.orderNumber + '</a>';
                    }},
                    { field: 'batchId', width: 180, title: '批次ID', sort: true },
                    { field: 'system', width: 80, title: '系统', sort: true },
                    { field: 'type', width: 100, title: '类型', sort: true },
                    { field: 'status', width: 100, title: '状态', sort: true, templet: '#statusTpl' },
                    { field: 'totalPoints', width: 100, title: '积分数量', sort: true },
                    { field: 'balanceCost', width: 100, title: '消耗余额', sort: true, templet: function(d) {
                        return d.balanceCost ? (d.balanceCost / 100).toFixed(2) : '0.00';
                    }},
                    { field: 'completedPoints', width: 100, title: '已完成积分', sort: true },
                    { field: 'progress', width: 100, title: '进度', sort: true, templet: function(d) {
                        return d.completedPoints + '/' + d.totalPoints;
                    }},
                    { field: 'externalId', width: 120, title: '外链ID', sort: true },
                    { field: 'remark', minWidth: 150, title: '备注', sort: true },
                    { field: 'createUserName', width: 100, title: '创建人', sort: true },
                    { field: 'createTime', width: 160, title: '创建时间', sort: true, templet: function (d) {
                        return dayjs(d.createTime).format('YYYY-MM-DD HH:mm:ss');
                    }},
                    { field: 'completeTime', width: 160, title: '完成时间', sort: true, templet: function (d) {
                        return d.completeTime ? dayjs(d.completeTime).format('YYYY-MM-DD HH:mm:ss') : '-';
                    }},
                    { field: 'cancelTime', width: 160, title: '取消时间', sort: true, templet: function (d) {
                        return d.cancelTime ? dayjs(d.cancelTime).format('YYYY-MM-DD HH:mm:ss') : '-';
                    }},
                    { title: '操作', minWidth: 200, toolbar: '#currentTableBar', align: "center", fixed: 'right' }
                ]],
                limits: [50, 200, 1000, 2000, 5000],
                limit: 50,
                page: true
            });

            // 监听搜索操作
            form.on('submit(data-search-btn)', function (data) {
                var result = JSON.stringify(data.field);
                tableIns.reload({
                    where: data.field,
                    page: {
                        curr: 1
                    }
                });
                return false;
            });

            // 工具栏事件
            table.on('toolbar(currentTableFilter)', function (obj) {
                if (obj.event === 'addOrder') {
                    openOrder({ uiType: "添加订单" });
                }
            });

            // 监听行工具事件
            table.on('tool(currentTableFilter)', function (obj) {
                const data = obj.data;
                if (obj.event === 'remark') {
                    layer.prompt({
                        title: '修改备注',
                        formType: 2,
                        value: data.remark || '',
                        area: ['400px', '200px']
                    }, function (value, index) {
                        axios.post('/order/remark', { orderId: data._id, remark: value })
                            .then(function (res) {
                                layer.close(index);
                                tableIns.reload();
                                layer.msg('备注修改成功！');
                            })
                            .catch(function (err) {
                                layer.msg('修改失败');
                            });
                    });
                } else if (obj.event === 'cancel') {
                    // 取消订单确认
                    layer.confirm('确定要取消此订单吗？如有未完成积分将按比例退款到余额。', {
                        title: '取消订单确认',
                        icon: 3
                    }, function (index) {
                        // 发送取消请求
                        axios.post('/order/cancel', { orderNumber: data.orderNumber })
                            .then(function (res) {
                                layer.close(index);
                                if (res.data.code === 1) {
                                    tableIns.reload();
                                    layer.msg(res.data.msg, { icon: 1 });
                                } else {
                                    layer.msg(res.data.msg, { icon: 2 });
                                }
                            })
                            .catch(function (err) {
                                layer.close(index);
                                layer.msg('取消订单失败', { icon: 2 });
                                console.error('取消订单错误:', err);
                            });
                    });
                } else if (obj.event === 'rescan') {
                    // 重扫确认，根据不同状态提供不同提示
                    let confirmMsg = '';
                    let confirmTitle = '重扫确认';
                    
                    if (data.status === '登陆失效') {
                        confirmMsg = '确定要重新扫码吗？此操作将删除当前登录信息，需要重新登录。';
                    } else if (data.status === '安全验证') {
                        confirmMsg = '确定要重新扫码吗？此操作将删除当前登录信息，需要重新进行安全验证。';
                    } else if (data.status === '进行中') {
                        confirmMsg = '订单正在进行中，确定要重新扫码吗？此操作可能会中断当前任务执行。';
                    } else if (data.status === '待处理') {
                        confirmMsg = '确定要重新扫码吗？此操作将删除当前登录信息，重新开始处理。';
                    }
                    
                    layer.confirm(confirmMsg, {
                        title: confirmTitle,
                        icon: 3,
                        btn: ['确定重扫', '取消']
                    }, function (index) {
                        // 发送重扫请求
                        axios.post('/order/rescan', { 
                            orderNumber: data.orderNumber,
                            status: data.status,
                            type: data.type
                        })
                            .then(function (res) {
                                layer.close(index);
                                if (res.data.code === 1) {
                                    tableIns.reload();
                                    layer.msg(res.data.msg, { icon: 1 });
                                } else {
                                    layer.msg(res.data.msg, { icon: 2 });
                                }
                            })
                            .catch(function (err) {
                                layer.close(index);
                                layer.msg('重扫操作失败', { icon: 2 });
                                console.error('重扫操作错误:', err);
                            });
                    });
                }
            });

            // 打开订单窗口函数
            function openOrder(data) {
                window.data = data;
                let index = layer.open({
                    title: data.uiType,
                    type: 2,
                    anim: 4,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['40%', '67%'],
                    content: './order-add.html',
                    end: function () {
                        window.data = null;
                        tableIns.reload();
                    }
                });
            }
        });
    </script>
</body>

</html>